<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :option="option"
      :table-loading="loading"
      :data="data"
      :page="page"
      :before-open="beforeOpen"
      :cell-style="cellStyle"
      :row-style="rowStyle"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @row-click="rowClick"
      @refresh-change="refresh"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          type="danger"
          size="medium"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
        >
          删 除
        </el-button>
      </template>
      <template slot="requestStatus" slot-scope="{row}">
        <el-tag :type="row.requestStatus===1? 'success': 'danger'">
          {{ row.requestStatus===1? '成功': '失败' }}
        </el-tag>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <el-button type="primary" icon="el-icon-plus" circle size="medium" />-->
      <!--      </template>-->
    </avue-crud>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex'

const addMonitorLogAction = 'log/addMonitorLog'
const updateMonitorLogAction = 'log/updateMonitorLog'
const removeMonitorLogAction = 'log/removeMonitorLog'
const removeMonitorLogsAction = 'log/removeMonitorLogs'
const getMonitorLogByIdAction = 'log/getMonitorLogById'
const getMonitorLogPageListAction = 'log/getMonitorLogPageList'

export default {
  name: 'LogBackend',
  data () {
    return {
      form: {},
      query: {
        operationType: 1
      },
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        // title: '日志表',
        border: true,
        menu: true,
        lazy: true,
        tip: true,
        tipPlacement: 'top-start',
        index: false,
        indexLabel: '序号',
        indexFixed: true,
        selection: true,
        selectionWidth: 60,
        selectionFixed: false,
        searchShow: false,
        addBtn: false,
        editBtn: false,
        viewBtn: true,
        excelBtn: false,
        printBtn: false,
        dialogDrag: true,
        dialogDirection: 'rtl',
        dialogType: 'dialog',
        column: [
          // {
          //   label: '请求者ID',
          //   prop: 'userName',
          //   type: 'text'
          // },
          {
            label: '操作来源',
            prop: 'operationType',
            type: 'select',
            hide: false,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入操作类别（0其它 1后台用户 2前台操作 3手机端用户）',
              trigger: 'blur'
            }],
            dicData: [
              {
                label: '其他',
                value: 0
              },
              {
                label: '后台接口',
                value: 1
              },
              {
                label: '前端UI',
                value: 2
              },
              {
                label: '手机端',
                value: 3
              }
            ]
          },
          {
            label: '模块名称',
            prop: 'businessTitle',
            type: 'input',
            hide: false,
            width: 150,
            span: 24,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入模块名称',
              trigger: 'blur'
            }]
          },
          {
            label: '业务类型',
            prop: 'businessType',
            type: 'select',
            hide: false,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入业务类型（0其它 1新增 2修改 3删除）',
              trigger: 'blur'
            }],
            dicData: [
              {
                label: '其他',
                value: 0
              },
              {
                label: '新增',
                value: 1
              },
              {
                label: '修改',
                value: 2
              },
              {
                label: '删除',
                value: 3
              }
            ]
          },
          {
            label: '接口方法名称',
            prop: 'method',
            type: 'input',
            hide: true,
            span: 24,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入方法名称',
              trigger: 'blur'
            }]
          },
          {
            label: '请求地址',
            prop: 'requestUrl',
            type: 'input',
            hide: false,
            width: 260,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入请求URL',
              trigger: 'blur'
            }]
          },
          {
            label: '操作时间',
            prop: 'updateTime',
            width: 150
          },
          {
            label: '请求参数',
            prop: 'requestParam',
            type: 'textarea',
            span: 24,
            hide: true,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入请求参数',
              trigger: 'blur'
            }]
          },
          {
            label: '返回结果',
            prop: 'requestStatus',
            type: 'select',
            hide: false,
            slot: true,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入操作状态（0正常 1异常）',
              trigger: 'blur'
            }],
            dicData: [
              {
                label: '失败',
                value: 0
              },
              {
                label: '成功',
                value: 1
              }
            ]
          },
          {
            label: '返回参数',
            prop: 'requestResult',
            type: 'textarea',
            span: 24,
            hide: true,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入返回参数',
              trigger: 'blur'
            }]
          },
          {
            label: '错误消息',
            prop: 'requestErrorMsg',
            type: 'textarea',
            span: 24,
            hide: true,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入错误消息',
              trigger: 'blur'
            }]
          },
          {
            label: '耗时(毫秒)',
            prop: 'requestTime',
            type: 'input',
            width: 100,
            hide: false,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入操作时间',
              trigger: 'blur'
            }],
            formatter (row, value, label, column) {
              return row.requestTime + '毫秒'
            }
          },
          {
            label: '请求IP',
            prop: 'requestIp',
            type: 'input',
            hide: false,
            width: 100,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入',
              trigger: 'blur'
            }]
          },
          {
            label: '请求方式',
            prop: 'requestMethod',
            type: 'input',
            hide: false,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入请求方式',
              trigger: 'blur'
            }]
          }
        ]
      },
      data: []
    }
  },
  computed: {
    ...mapGetters(['permissions', 'website']),
    ids () {
      const ids = []
      this.selectionList.forEach((e) => {
        ids.push(e.id)
      })
      return ids
    }
  },
  methods: {
    rowStyle ({ row, column, rowIndex }) {
      return {}
    },
    cellStyle ({ row, column, rowIndex, columnIndex }) {
      // return {
      //   color: 'green',
      //   fontWeight: 'bold',
      //   fontSize: '20'
      // }
      return {}
    },
    rowSave (row, loading, done) {
      loading()
      this.$store.dispatch(addMonitorLogAction, row).then((res) => {
        done()
        const resCode = res.code
        const message = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '保存操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: message || '保存数据失败,请稍后再试!'
          })
        }
      }).catch(() => {
        done()
        this.$message({
          type: 'error',
          showClose: true,
          message: '保存数据失败,请稍后再试!'
        })
      })
    },
    rowUpdate (row, index, loading, done) {
      loading()
      this.$store.dispatch(updateMonitorLogAction, row).then((res) => {
        done()
        const resCode = res.code
        const message = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '编辑操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: message || '编辑数据失败,请稍后再试!'
          })
        }
      }).catch(() => {
        done()
        this.$message({
          type: 'error',
          showClose: true,
          message: '编辑数据异常,请稍后再试!'
        })
      })
    },
    rowDel (row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { id: row.id }
          return this.$store.dispatch(removeMonitorLogAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const message = res.message
          if (resCode === 0) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '删除操作成功!'
            })
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: message || '删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {
          this.loading = false
        })
    },
    handleDelete () {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { ids: this.ids }
          return this.$store.dispatch(removeMonitorLogsAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const message = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '批量删除操作成功!'
            })
            this.onLoad(this.page)
            this.$refs.crud.toggleSelection()
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: message || '批量删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {
          this.loading = false
          this.$message({
            type: 'error',
            showClose: true,
            message: '批量删除数据异常,请稍后再试!'
          })
        })
    },
    rowClick (row, event, column) {
      this.$refs.crud.rowView(row, column)
    },
    refresh ({ page, searchForm }) {
      this.onLoad(page)
    },
    beforeOpen (done, type) {
      if (['edit', 'view'].includes(type)) {
        const idParams = { id: this.form.id }
        this.$store.dispatch(getMonitorLogByIdAction, idParams).then((res) => {
          const resCode = res.code
          const message = res.message
          if (resCode === 0) {
            this.form = res.data
          } else {
            this.$message({
              type: 'error',
              showClose: true,
              message: message || '查询数据失败,请稍后再试!'
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            showClose: true,
            message: '查询数据异常,请稍后再试!'
          })
        })
      }
      done()
    },
    searchReset () {
      this.query = {}
      this.onLoad(this.page)
    },
    searchChange (params, done) {
      done()
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
    },
    selectionChange (list) {
      this.selectionList = list
    },
    selectionClear () {
      this.selectionList = []
      this.$refs.crud.toggleSelection()
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    onLoad (page, params = {}) {
      this.loading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize
      }
      queryData = Object.assign(queryData, Object.assign(params, this.query))
      this.$store.dispatch(getMonitorLogPageListAction, queryData).then((res) => {
        this.loading = false
        const resCode = res.code
        const message = res.message
        if (resCode === 0) {
          const data = res.data
          this.page.total = parseInt(data.total)
          this.data = data.records
          this.selectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: message || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    }
  },
  head () {
    return {
      title: '后台接口日志管理 | ' + this.website.name,
      meta: [
        { hid: 'description', name: 'description', content: '后台接口日志管理' }
      ]
    }
  }
}
</script>

<style>
</style>
